<template class="firstpage">
  <div>
    <div class="boxMargin" @click="ladingRegion">
      <el-card class="box-card">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">货号：</el-col>
              <el-checkbox
                v-model.trim="customData.hostItemsType"
                style="position: absolute; left: 0px; top: 37px"
                @change="hostItemTypeChange($event)"
              >模糊匹配</el-checkbox>
              <el-col :span="14">
                <el-input
                  v-model="customData.hostItem"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入货号，可多货号一起查询，以回车换行分割"
                  @input="hostItemChange($event)"
                />
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">商品名称：</el-col>
              <el-col :span="14">
                <el-input
                  v-model.trim="searchData.itemName"
                  placeholder="请输入商品名称"
                />
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">品牌名称：</el-col>
              <el-col :span="14">
                <el-select
                  v-model="searchData.brandId"
                  placeholder="请选择"
                  filterable
                  remote
                  reserve-keyword
                  :remote-method="brandNameChange"
                  :loading="customData.loading"
                  @change="brandNameNo"
                >
                  <el-option
                    v-for="item in customData.brandNameList"
                    :key="item.brandId"
                    :label="item.brandName"
                    :value="item.brandId"
                  />
                </el-select>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row class="margin" :gutter="20">
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">商品分类：</el-col>
              <el-col :span="14">
                <el-input
                  v-model="customData.categoryName"
                  :readonly="true"
                  placeholder="请选择"
                  @click.stop.native="inputFocus"
                />
                <div v-if="customData.treeModel" class="tree-div">
                  <el-input
                    v-model="filterText"
                    placeholder="请输入关键字搜索"
                    style="width: 85%; margin-top: 5px; margin-left: 8px"
                    @click.stop.native="inputFocus"
                  />
                  <el-tree
                    ref="tree"
                    class="tree"
                    accordion
                    :data="customData.categoryListTree"
                    node-key="categoryId"
                    :props="customData.defaultProps"
                    :filter-node-method="filterNode"
                    @click.stop
                    @node-click="handleNodeClick"
                  />
                </div>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">上架状态：</el-col>
              <el-col :span="14">
                <el-select v-model="searchData.isShelf" placeholder="请选择">
                  <el-option
                    v-for="task in customData.isShelf"
                    :key="task.value"
                    :label="task.label"
                    :value="task.value"
                  />
                </el-select>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">是否推荐：</el-col>
              <el-col :span="14">
                <el-select
                  v-model="searchData.isRecommend"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="task in customData.wheather"
                    :key="task.value"
                    :label="task.label"
                    :value="task.value"
                  />
                </el-select>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row class="margin" :gutter="20">
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">是否置顶：</el-col>
              <el-col :span="14">
                <el-select v-model="searchData.isTopping" placeholder="请选择">
                  <el-option
                    v-for="task in customData.wheather"
                    :key="task.value"
                    :label="task.label"
                    :value="task.value"
                  />
                </el-select>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">是否精选：</el-col>
              <el-col :span="14">
                <el-select v-model="searchData.isSelected" placeholder="请选择">
                  <el-option
                    v-for="task in customData.wheather"
                    :key="task.value"
                    :label="task.label"
                    :value="task.value"
                  />
                </el-select>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">是否可售：</el-col>
              <el-col :span="14">
                <el-select v-model="searchData.isSale" placeholder="请选择">
                  <el-option
                    v-for="task in customData.wheather"
                    :key="task.value"
                    :label="task.label"
                    :value="task.value"
                  />
                </el-select>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row class="margin" :gutter="20">
          <el-col :span="8">
            <el-row>
              <el-col :span="8" class="inputName">门店：</el-col>
              <el-col :span="14">
                <el-select v-model="searchData.storeId" placeholder="请选择">
                  <el-option
                    v-for="task in customData.dropDownList"
                    :key="task.storeId"
                    :label="task.storeName"
                    :value="task.storeId"
                  />
                </el-select>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row class="margin">
          <el-col :span="24" class="right">
            <el-button type="success" @click="onSearch">查询</el-button>
            <el-button @click="onReset">清空</el-button>
          </el-col>
        </el-row>
      </el-card>
    </div>
    <div class="boxMargin">
      <el-card class="box-card">
        <div slot="header">
          <div class="contion-header" style="width: 10%">
            <span>门店商品列表</span>
          </div>
          <div class="contion-header text-r" style="width: 89%">
            <el-button type="primary" @click.native="onAdd">新增商品</el-button>
          </div>
        </div>
        <div>
          <el-table
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            :header-cell-style="{'background':'#f8f8f9'}"
            border
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="displayUrl" label="商品图片" width="100px">
              <template slot-scope="scope">
                <div
                  v-if="
                    scope.row.displayUrl != undefined &&
                      scope.row.displayUrl != null &&
                      scope.row.displayUrl != ''
                  "
                  class="display-img"
                >
                  <img
                    :src="scope.row.displayUrl"
                    alt=""
                    style="max-width: 100%; max-height: 100%"
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="skuCode" label="商品货号" />
            <el-table-column prop="itemName" label="商品名称" />
            <el-table-column prop="itemPriceDouble" label="单价(元)" />
            <el-table-column prop="itemStock" label="库存" />
            <el-table-column prop="upCode" label="商品条码" />
            <el-table-column
              prop="categoryName"
              label="商品分类"
            />
            <el-table-column prop="brandName" label="品牌" />
            <el-table-column
              prop="storeName"
              label="门店名称"
            />
            <el-table-column prop="isShelf" label="上架状态">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isShelf"
                  :active-value="1"
                  :inactive-value="0"
                  @change="isShelfStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="isRecommend" label="是否推荐">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isRecommend"
                  :active-value="1"
                  :inactive-value="0"
                  @change="isRecommendStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="isTopping" label="是否置顶">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isTopping"
                  :active-value="1"
                  :inactive-value="0"
                  @change="isToppingStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="isSelected" label="是否精选">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isSelected"
                  :active-value="1"
                  :inactive-value="0"
                  @change="isSelectedStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column prop="isSale" label="是否可售">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.isSale"
                  :active-value="1"
                  :inactive-value="0"
                  @change="isSaleStatusChange(scope.row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click.native="onUpdate(scope.row)">编辑</el-button>
              </template>
            </el-table-column>

            <!--            <el-table-column label="操作" width=50px">-->
            <!--              <template slot-scope="scope">-->
            <!--                <el-button type="text" @click="onInfo(scope.row)"-->
            <!--                  >查看</el-button-->
            <!--                >-->
            <!--                <el-button type="text" @click.native="onUpdate(scope.row)"-->
            <!--                  >编辑</el-button-->
            <!--                >-->
            <!--              </template>-->
            <!--            </el-table-column>-->
          </el-table>
        </div>
      </el-card>
      <div class="marginTop20 center">
        <template>
          <PAGER ref="wptxPager" @search="onChangePage" />
        </template>
      </div>
    </div>
    <div>
      <ADD ref="storeitemAdd" />
    </div>
    <div>
      <EDIT ref="storeitemEdit" />
    </div>
  </div>
</template>
<script>
import $ from 'jquery'
import _validate from '../../../../framework/commonJs/wptx_validate'
import _tools from '../../../../framework/commonJs/wptx_tools'
import _api from '../../../../framework/API/storeItem'
import _allApi from '../../../../framework/API/apiAll'
import ADD from './storeitemCrud/storeitem_add'
import EDIT from './storeitemCrud/storeitem_edit'
import { reportingGeneral } from '../../../../framework/API/excel'
import { PAGER } from '@/framework/commonTemplate/'
const _FUNCTION_NAME = ''
export default {
  components: { PAGER, ADD, EDIT },
  filters: {},
  data() {
    return {
      tableData: [],
      searchData: {
        skuCodes: '', // 货号
        upCodes: '', // Hostupc
        itemName: '', // 商品名称
        brandId: '', // 品牌名称
        categoryId: '',
        hostItemsType: 1,
        upCodesType: 1,
        productVirtiualType: '',
        itemStatusCode: '',
        isShelf: '',
        isRecommend: '',
        isTopping: '',
        isSelected: '',
        isSale: '',
        storeId: ''
      },
      searchDataBuffer: {
        skuCodes: '', // 货号
        upCodes: '', // Hostupc
        itemName: '', // 商品名称
        brandId: '', // 品牌名称
        categoryId: '',
        hostItemsType: 1,
        upCodesType: 1,
        productVirtiualType: '',
        itemStatusCode: '',
        isShelf: '',
        isRecommend: '',
        isTopping: '',
        isSelected: '',
        isSale: '',
        storeId: ''
      },
      pageData: {
        pageNo: 1,
        pageSize: 10,
        total: 1,
        pageSizes: [10, 20, 50, 100]
      },
      historyData: {},
      infoData: {},
      dialogData: {
        isHost: false
      },
      customData: {
        commodityType: [
          { label: '请选择', value: '' },
          { label: '虚拟商品', value: 5 },
          { label: '普通商品', value: 0 }
        ],
        isShelf: [
          { label: '关闭', value: 0 },
          { label: '开启', value: 1 }
        ],
        wheather: [
          { label: '否', value: 0 },
          { label: '是', value: 1 }
        ],
        dropDownList: [],
        hostItem: '',
        hostUpc: '',
        brandNameList: [],
        brandName: '',
        loading: false,
        treeModel: false,
        categoryName: '',
        categoryListTree: [],
        defaultProps: {
          children: 'childTreeDto',
          label: 'categoryName'
        },
        multipleSelection: [],
        hostItemsType: false,
        upCodesType: false,
        releaseModel: false,
        productVirtiualModel: false,
        getWmHostItem: [],
        getHostUpc: '',
        getData: []
      },
      filterText: '',
      form: {},
      rules: {}
    }
  },
  computed: {},
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() { },
  mounted() {
    this._FUNCTION_NAME = this.$route.name
    this.onInit()
    const params = {
    }
    _allApi.categroyTreeList(this, params, this.callBack_categroyTreeList)
    this.dropDownList()
  },
  beforeDestroy() { },
  methods: {
    onInit(data) {
      const self = this
      let page = sessionStorage.getItem('pageCondition')
      let search = sessionStorage.getItem('searchCondition')
      let tree = sessionStorage.getItem('treeCondition')
      const brand = sessionStorage.getItem('brandCondition')
      if (!_validate.checkListEmpty(tree)) {
        tree = JSON.parse(tree)
        self.customData.categoryName = tree.categoryName
      }
      if (!_validate.checkListEmpty(page)) {
        page = JSON.parse(page)
        self.$refs.wptxPager.pageData = page
      }
      if (!_validate.checkListEmpty(search)) {
        search = JSON.parse(search)
        self.searchData = search
        if (self.searchData.hostItemsType == 0) { // hostItem 的模糊匹配
          self.customData.hostItemsType = true
        } else {
          self.customData.hostItemsType = false
        }
        if (!_validate.checkEmpty(self.searchData.skuCodes)) { // hostItem
          self.customData.hostItem = _tools.commaTo(self.searchData.skuCodes)
        }
        if (self.searchData.upCodesType == 0) { // Hostupc 的模糊匹配
          self.customData.upCodesType = true
        } else {
          self.customData.upCodesType = false
        }
        if (!_validate.checkEmpty(self.searchData.upCodes)) { // Hostupc
          self.customData.hostUpc = _tools.commaTo(self.searchData.upCodes)
        }
        if (!_validate.checkEmpty(self.searchData.brandId)) { // 查询品牌列表
          self.brandNameChange(brand)
        }
        self.searchDataBuffer = _tools.cloneObj(self.searchData)
        self.onChangePage()
      } else {
        _api.page(self, self.$refs.wptxPager.pageData, self.callBack_page, self.searchData)
      }
    },
    onSearch(data) {
      const self = this
      const params = {}
      $.each(self.searchData, function(name, val) {
        if (val != undefined && val != null && $.trim(val) != '') {
          params[name] = val
        }
      })
      self.searchDataBuffer = _tools.cloneObj(self.searchData)
      self.$refs.wptxPager.resetPageNo()
      sessionStorage.setItem('searchCondition', JSON.stringify(self.searchData))
      const page = self.$refs.wptxPager.pageData
      sessionStorage.setItem('pageCondition', JSON.stringify(page))
      const tree = {
        categoryName: self.customData.categoryName,
        filterText: self.filterText
      }
      sessionStorage.setItem('treeCondition', JSON.stringify(tree))
      sessionStorage.setItem('brandCondition', self.customData.brandName)
      _api.page(self, self.$refs.wptxPager.pageData, self.callBack_page, params)
    },
    onChangePage(data) {
      const self = this
      const params = self.searchDataBuffer
      const page = self.$refs.wptxPager.pageData
      sessionStorage.setItem('pageCondition', JSON.stringify(page))
      _api.page(self, self.$refs.wptxPager.pageData, self.callBack_page, params)
    },
    onReset(data) {
      const self = this
      _tools.reset(self.searchData)
      _tools.reset(self.searchDataBuffer)
      self.customData.hostItem = ''
      self.customData.hostUpc = ''
      self.customData.categoryName = ''
      self.filterText = ''
      self.searchData.categoryId = ''
      self.$refs.wptxPager.pageData.pageNo = 1
      self.$refs.wptxPager.pageData.total = 0
      self.tableData = []
      self.searchData.hostItemsType = 1
      self.searchData.upCodesType = 1
      self.customData.hostItemsType = false
      self.customData.upCodesType = false
      self.customData.productVirtiualModel = false
      sessionStorage.removeItem('searchCondition')
      sessionStorage.removeItem('pageCondition')
      sessionStorage.removeItem('treeCondition')
      sessionStorage.removeItem('brandCondition')
      self.onChangePage()
    },
    onAdd() {
      const self = this
      self.$refs.storeitemAdd.show()
    },
    onDelete(data) {
      const self = this
    },
    onInfo(data) {
      const self = this
      self.$router.push({
        path: '/item/itemDetail',
        query: {
          itemId: data.itemId,
          itemVersionId: data.versionId,
          productType: data.productType
        }
      })
    },
    onUpdate(data) {
      const self = this
      self.$refs.storeitemEdit.show({ ...data })
    },
    onBathDelete() {
      const self = this
    },
    onBathUpdate() { },
    onDisable(data) {
      const self = this
    },
    onEnable(data) {
      const self = this
    },
    onUpload(data) { },
    onBathUpload() { },
    onExport(data) { },
    onDownload(data) { },
    onHistory(data) { },
    callBack_page(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        self.tableData = data.result
        self.$refs.wptxPager.updatePageData(data)
      }
    },
    callBack_brandSelect(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        self.customData.loading = false
        self.customData.brandNameList = data.data.result
      }
    },
    callBack_categroyTreeList(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        self.customData.categoryListTree = data.data
      }
    },
    callBack_taskCreate(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '操作超时，请刷新页面后重试', 'warning')
      } else {
        _validate.openTip(self, data.data, 'success')
        self.customData.releaseModel = false
        self.onChangePage()
      }
    },
    callBack_getWmHostItem(data) {
      const self = this
      if (_validate.checkListEmpty(data.result.data)) {
        self.customData.getWmHostItem = []
      } else {
        self.customData.getWmHostItem = data.result.data
      }
    },
    callBack_saveWmHostItemWM(data) {
      const self = this
      if (data.code == 200) {
        _tools.openTip(self, data.result.data.msg, 'success')
        self.dialogData.isHost = false
        self.customData.getData = []
        self.customData.getHostUpc = ''
        self.customData.getWmHostItem = []
        self.onInit()
      } else {
        _tools.openTip(self, data.message, 'error')
        return false
      }
    },
    callBack_dropDownList(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '获取超时，请稍后重试', 'warning')
      } else {
        self.customData.dropDownList = data.data
      }
    },
    hostItemChange(value) {
      const self = this
      self.searchData.skuCodes = _tools.enter(value)
    },
    hostItemTypeChange(value) {
      const self = this
      if (value) {
        self.searchData.hostItemsType = 0
      } else {
        self.searchData.hostItemsType = 1
      }
    },
    hostUpcChangeTypeChange(value) {
      const self = this
      if (value) {
        self.searchData.upCodesType = 0
      } else {
        self.searchData.upCodesType = 1
      }
    },
    hostUpcChange(value) {
      const self = this
      self.searchData.upCodes = _tools.enter(value)
    },
    brandNameChange(query) {
      const self = this
      if (!_tools.blankSpace(query)) {
        self.customData.loading = true
        const params = {
          brandName: query
        }
        setTimeout(function() {
          _allApi.brandSelect(self, params, self.callBack_brandSelect)
        }, 1000)
      } else {
        self.customData.brandNameList = []
      }
    },
    brandNameNo() {
      const self = this
      for (let i = 0; i < self.customData.brandNameList.length; i++) {
        if (self.customData.brandNameList[i].brandId == self.searchData.brandId) {
          self.customData.brandName = self.customData.brandNameList[i].brandName
        }
      }
    },
    inputFocus() {
      const self = this
      self.customData.treeModel = true
    },
    ladingRegion() {
      this.customData.treeModel = false
    },
    handleNodeClick(data) {
      const self = this
      self.customData.categoryName = data.categoryName
      self.searchData.categoryId = data.categoryId
    },
    filterNode(value, data) {
      if (!value) return true
      return data.categoryName.indexOf(value) !== -1
    },
    handleSelectionChange(val) {
      this.customData.multipleSelection = val
    },
    report() {
      const self = this
      let params = {}
      const num = []
      if (self.customData.multipleSelection.length == 0) {
        params = self.searchData
      } else {
        self.customData.multipleSelection.forEach(item => {
          num.push(item.itemId)
        })
        params.itemIds = num.join(',')
      }
      const time = _tools.getTime()
      const title = 'itemInfo_' + time + '.xlsx'
      reportingGeneral(params).then(res => {
        if (!_validate.checkEmpty(res.data)) {
          _validate.downloadNotFileName(res, title)
        }
      }).catch(error => {
      })
    },
    isShelfStatusChange(row) {
      const self = this
      const params = {
        'storeItemId': row.id,
        'isShelf': row.isShelf
      }
      _api.shelfValue(self, params, self.callBack_updateAttrValue)
    },
    isRecommendStatusChange(row) {
      const self = this
      const params = {
        'storeItemId': row.id,
        'isRecommend': row.isRecommend
      }
      _api.isRecommendValue(self, params, self.callBack_updateAttrValue)
    },
    isToppingStatusChange(row) {
      const self = this
      const params = {
        'storeItemId': row.id,
        'isTopping': row.isTopping
      }
      _api.toppingValue(self, params, self.callBack_updateAttrValue)
    },
    isSelectedStatusChange(row) {
      const self = this
      const params = {
        'storeItemId': row.id,
        'isSelected': row.isSelected
      }
      _api.selectedValue(self, params, self.callBack_updateAttrValue)
    },
    isSaleStatusChange(row) {
      const self = this
      const params = {
        'storeItemId': row.id,
        'isSale': row.isSale
      }
      _api.saleValue(self, params, self.callBack_updateAttrValue)
    },
    callBack_updateAttrValue(data) {
      const self = this
      if (_validate.checkEmpty(data)) {
        _validate.openTip(self, '返回数据为空', 'warning')
      } else {
        _validate.openTip(self, '保存成功', 'success')
        self.onInit()
      }
    },
    dropDownList() {
      const self = this
      const params = {}
      _api.dropDownUpdate(self, params, self.callBack_dropDownList)
    }
  }
}
</script>
<style lang="scss" scoped>
.contion-header {
  display: inline-block;
  box-sizing: border-box;
}
.text-r {
  text-align: right;
}
.tree-div {
  position: absolute;
  height: auto;

  z-index: 10;
  overflow-y: scroll;
  width: 58%;
  background: #eee;
}
.tree {
  max-height: 200px;

  background: #eee;
}
.el-card {
  overflow: visible;
}
.display-img {
  width: 50px;
  height: 50px;
  border-radius: 6px;
  text-align: center;
}
</style>
